package cn.com.dcsgo.config;

import cn.com.dcsgo.constant.AuthConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 远程调用拦截器，给远程调用请求添加带认证信息的请求头
 *
 * @author Dcsgo
 * @since 2025/10/28 18:12
 */
@Slf4j
@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     * 给远程调用请求添加带认证信息的请求头
     *
     * @param requestTemplate 远程调用的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 服务消费消息时走RPC会没有请求头
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        requestTemplate.header(AuthConstant.AUTHORIZATION, request.getHeader(AuthConstant.AUTHORIZATION));
    }
}
